
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.Domain.Repositories;
using L._52ABP.Application.Dtos;
using L._52ABP.Common.Extensions.Enums;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.BusinessLogic.Exporting;
using Yozeev.BusinessLogic.DomainService;
using Yozeev.BusinessLogic.Authorization;

namespace Yozeev.BusinessLogic
{
    /// <summary>
    /// 应用层服务的接口实现方法
    ///</summary>
    [AbpAuthorize]
    public class CommonCustomerAppService : YozeevAppServiceBase, ICommonCustomerAppService
    {
         private readonly IRepository<CommonCustomer, Guid> _commonCustomerRepository;
		private readonly IRepository<Customer, Guid> _customerRepository;
		private readonly ICommonCustomerListExcelExporter _commonCustomerListExcelExporter; 
		private readonly IEnumExtensionsAppService _enumExtensionsAppService;
		private readonly ICommonCustomerManager _commonCustomerManager;
		private readonly CustomerManager _customerManager;
		/// <summary>
		/// 构造函数
		///</summary>
		public CommonCustomerAppService(
		IRepository<CommonCustomer, Guid>  commonCustomerRepository
              ,ICommonCustomerManager commonCustomerManager       
,CommonCustomerListExcelExporter commonCustomerListExcelExporter              
			, IEnumExtensionsAppService enumExtensionsAppService       
			, CustomerManager customerManager
			, IRepository<Customer, Guid> customerRepository
			 )
            {
            _commonCustomerRepository = commonCustomerRepository;
             _commonCustomerManager=commonCustomerManager;;
_commonCustomerListExcelExporter = commonCustomerListExcelExporter;           
			_enumExtensionsAppService = enumExtensionsAppService;
			_customerManager = customerManager;
			_customerRepository = customerRepository;
            }


        /// <summary>
        /// 获取的分页列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<CommonCustomerListDto>> GetPaged(GetCommonCustomersInput input)
		{
			var query = from commonCustomer in _commonCustomerRepository.GetAll()
						join customer in _customerRepository.GetAll()
				   .WhereIf(!string.IsNullOrEmpty(input.OpenId), m => m.OpenID == input.OpenId)
				   on commonCustomer.MainCustomerId equals customer.Id
						select commonCustomer
			;
			// TODO:根据传入的参数添加过滤条件

			var count = await query.CountAsync();

			var commonCustomerList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

		  var commonCustomerListDtos = ObjectMapper.Map<List<CommonCustomerListDto>>(commonCustomerList);

			return new PagedResultDto<CommonCustomerListDto>(count,commonCustomerListDtos);
		}


		/// <summary>
		/// 通过指定id获取CommonCustomerListDto信息
		/// </summary>
		public async Task<CommonCustomerListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _commonCustomerRepository.GetAsync(input.Id);

			var dto = ObjectMapper.Map<CommonCustomerListDto>(entity);
			return dto;
 		}

		/// <summary>
		/// 获取编辑 
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetCommonCustomerForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetCommonCustomerForEditOutput();
CommonCustomerEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _commonCustomerRepository.GetAsync(input.Id.Value);
				editDto = ObjectMapper.Map<CommonCustomerEditDto>(entity);
			}
			else
			{
				editDto = new CommonCustomerEditDto();
			}
    

            output.CommonCustomer = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdateCommonCustomerInput input)
		{

			if (input.CommonCustomer.Id.HasValue)
			{
				await Update(input.CommonCustomer);
			}
			else
			{
				await Create(input.CommonCustomer);
			}
		}


		/// <summary>
		/// 新增
		/// </summary>
		protected virtual async Task<CommonCustomerEditDto> Create(CommonCustomerEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<CommonCustomer>(input);
            //调用领域服务
            entity = await _commonCustomerManager.CreateAsync(entity);

            var dto=ObjectMapper.Map<CommonCustomerEditDto>(entity);
            return dto;
		}

		/// <summary>
		/// 编辑
		/// </summary>
		protected virtual async Task Update(CommonCustomerEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

		 var entity = await _commonCustomerRepository.GetAsync(input.Id.Value);
          //  input.MapTo(entity);
          //将input属性的值赋值到entity中
             ObjectMapper.Map(input, entity);
            await _commonCustomerManager.UpdateAsync(entity);
		}

		/// <summary>
		/// 删除信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
            await _commonCustomerManager.DeleteAsync(input.Id);
		}

		/// <summary>
		/// 批量删除CommonCustomer的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
            await _commonCustomerManager.BatchDelete(input);
		}
		
		/// <summary>
		/// 导出为excel文件
		/// </summary>
		/// <returns></returns>
		public async Task<FileDto> GetToExcelFile()
		{
		   var commonCustomers = await _commonCustomerManager.QueryCommonCustomers().ToListAsync();
            var commonCustomerListDtos = ObjectMapper.Map<List<CommonCustomerListDto>>(commonCustomers);
            return _commonCustomerListExcelExporter.ExportToExcelFile(commonCustomerListDtos);
		}
		/// <summary>
		/// 创建常用游客
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateCommonCustomer(CreateOrUpdateCommonCustomerInput input)
		{
			var commonCustomer = input.CommonCustomer.MapTo<CommonCustomer>();
			//判断游客表中是否存在该证件号的游客
			var customer = await _customerManager.GetByIdentityNo(input.CommonCustomer.CertificatesNum);
			if (customer ==null || customer.Id==Guid.Empty )
			{
				//新增游客表
				customer = ObjectMapper.Map<Customer>(input.CommonCustomer);
				customer = await _customerManager.CreateAsync(customer);   
			}
			//给常用游客副游客赋值
			commonCustomer.ViceCustomerId = customer.Id;
			//创建常用游客
			await _commonCustomerRepository.InsertAndGetIdAsync(commonCustomer);
		}
    }
}


